package com.dikang.keer.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dikang.common.to.SkuReductionTo;
import com.dikang.common.utils.PageUtils;
import com.dikang.common.utils.Query;
import com.dikang.common.utils.R;
import com.dikang.keer.wms.dao.WareSkuDao;
import com.dikang.keer.wms.entity.WareSkuEntity;
import com.dikang.keer.wms.feign.ProductFeignService;
import com.dikang.keer.wms.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;
@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity>
    implements WareSkuService {
  @Resource
  private WareSkuDao wareSkuDao;
  @Autowired
  private ProductFeignService productFeignService;

  /**
   * skuId:1 wareId:2
   *
   * @param params
   * @return
   */
  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    String wareId = (String) params.get("wareId");
    String skuId = (String) params.get("skuId");
    QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<WareSkuEntity>();
    if (!StringUtils.isEmpty(wareId)) {
      wrapper.eq("ware_id", wareId);
    }
    if (!StringUtils.isEmpty(skuId)) {
      wrapper.eq("sku_id", skuId);
    }

    IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), wrapper);

    return new PageUtils(page);
  }

  @Override
  public void addStock(Long skuId, Long wareId, Integer skuNum) {
    // 判断是否有这个库存记录
    Integer count =
        baseMapper.selectCount(
            new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
    
    if (count != 0 || count!=null) {
      wareSkuDao.addStock(skuId, wareId, skuNum);
    }else{
        WareSkuEntity wareSkuEntity = new WareSkuEntity();
        wareSkuEntity.setSkuId(skuId);
        // TODO 调用productFeign去查询出商品信息
       try{
           R r = productFeignService.getSkuInfo(skuId);
           Map<String,Object> data = (Map<String, Object>) r.get("skuInfo");
          if ( r.getCode()==0){
              wareSkuEntity.setSkuName((String) data.get("skuName"));
          }
       }catch (Exception e){
           // 查询失败无需回滚
           log.info("远程调用proctFeignService失败，无需回滚");
       }

        wareSkuEntity.setStock(skuNum);
        wareSkuEntity.setStockLocked(0);
        wareSkuEntity.setWareId(wareId);
        baseMapper.insert(wareSkuEntity);
    }
  }
}
